import { axios, service, PATH_URL } from './service'
import jsonpAdapter from 'axios-jsonp'
import { CancelToken } from 'axios'

import { config } from './config'

const { default_headers } = config
const cancelAxiosFnAry = [] // 存储取消请求的方法数组，内格式为[{ key, fn }, { key, fn }]

const request = (option) => {
  const {
    url,
    method,
    params,
    data,
    headersType,
    responseType,
    noPrefix,
    noHeaders,
    noErrorHint,
    cancelFn,
    repeatCancel = false, // 取消重复请求
    cancelToken: defaultCancelToken
  } = option
  const headers = {
    'X-Requested-With': 'XMLHttpRequest',
    'Authorization': localStorage.getItem("token") || '',
    'Content-Type': headersType || default_headers
  }
  const serviceOptions = {
    url,
    method,
    params,
    data,
    responseType
  }

  // 封装axios的取消方法，使用时就不用去引入CancelToken了
  if (defaultCancelToken) {
    serviceOptions['cancelToken'] = defaultCancelToken
  } else if (typeof cancelFn === 'function') {
    serviceOptions['cancelToken'] = new CancelToken((cancel) => cancelFn(cancel))
  } else if (repeatCancel) {
    const cancelKey = url.indexOf('?') > -1 ? url.substring(0, url.indexOf('?')) : url
    for (let i = cancelAxiosFnAry.length - 1; i > 0; i--) {
      const { key, fn } = cancelAxiosFnAry[i]
      if (key === cancelKey) {
        fn()
        cancelAxiosFnAry.splice(i, 1)
        break
      }
    }
    serviceOptions['cancelToken'] = new CancelToken((cancel) => {
      cancelAxiosFnAry.push({ key: cancelKey, fn: cancel })
    })
  }
  // 不需要headers
  if (noHeaders !== true) {
    serviceOptions['headers'] = headers
  }
  // 不需要接口前缀
  if (noPrefix) {
    serviceOptions['baseURL'] = PATH_URL.replace(/\/v1/, '')
  }

  // 不需要接口错误提示
  if (noErrorHint) {
    serviceOptions['noErrorHint'] = noErrorHint
  }

  return service(serviceOptions)
}
export default {
  get: (option) => {
    return request({ method: 'get', ...option })
  },
  getV2: (option) => {
    return request({ method: 'get', noPrefix: true, ...option })
  },
  post: (option) => {
    return request({ method: 'post', ...option })
  },
  postV2: (option) => {
    return request({ method: 'post', noPrefix: true, ...option })
  },
  jsonp: (option) => {
    return axios({ adapter: jsonpAdapter, ...option })
  }
  // delete: (option) => {
  //   return request({ method: 'delete', ...option })
  // },
  // put: (option) => {
  //   return request({ method: 'put', ...option })
  // }
}
